package com.building18.controller;

import com.building18.handler.MyAssert;
import com.building18.pojo.MyPageData;
import com.building18.pojo.Result;
import com.building18.pojo.Role;
import com.building18.pojo.User;
import com.building18.pojo.enums.Code;
import com.building18.pojo.vo.RoleVO;
import com.building18.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@Tag(name = "角色管理", description = "角色管理")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("/{id}")
    @Operation(summary = "根据用户id查询角色类型")
    public Result<?> getRoles(@PathVariable("id") Integer id) {
        List<RoleVO> roles = roleService.getRoles(id);
        return Result.ok(roles, Code.SELECT_SUCCESS.getMessage());
    }

    @PostMapping("/saveRole/{id}")
    @Operation(summary = "保存用户的角色类型")
    public Result<?> saveRole(@PathVariable("id") Integer id, @RequestBody List<Integer> roleIds) {
        Integer i = roleService.saveRole(id, roleIds);
        MyAssert.error(i<=0,Code.UPDATE_FAIL.getMessage());
        return Result.ok(i,Code.UPDATE_SUCCESS.getMessage());
    }

    @GetMapping("/{pageNum}/{pageSize}")
    @Operation(summary = "分页查询角色")
    public Result<?> selectRoles(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<RoleVO> roles =roleService.selectRoles();
        PageInfo<RoleVO> roleVOPageInfo = new PageInfo<>(roles);
        MyPageData myPageData=new MyPageData(roleVOPageInfo.getTotal(),roleVOPageInfo.getList());
        return Result.ok(myPageData, Code.SELECT_SUCCESS.getMessage());
    }

    @DeleteMapping("/deleteRole/{id}")
    @Operation(summary = "删除角色")
    public Result<?> deleteRole(@PathVariable Integer id){
        Integer i = roleService.deleteRole(id);
        MyAssert.error(i<=0,Code.DELETE_FAIL.getMessage());
        return Result.ok(i,Code.DELETE_SUCCESS.getMessage());
    }

    @PostMapping("/updateRole")
    @Operation(summary = "修改角色")
    public Result<?> updateRole(@RequestBody Role role){
        Integer i = roleService.updateRole(role);
        MyAssert.error(i<=0,Code.UPDATE_FAIL.getMessage());
        return Result.ok(i,Code.UPDATE_SUCCESS.getMessage());
    }

    @GetMapping("/selectRole/{id}")
    @Operation(summary = "查询角色所有信息")
    public Result<?> selectRole(@PathVariable("id") Integer id){
        Role role = roleService.selectRole(id);
        return Result.ok(role,Code.SELECT_SUCCESS.getMessage());
    }

}
